import express from "express";
import {
  addComment as addCommentTorrent,
  addVote,
  deleteTorrent,
  fetchTorrent,
  fetchTorrentDetailsByID,
  listLatest,
  listAll,
  removeVote,
  searchTorrents,
  toggleFreeleech,
  uploadTorrent,
  editTorrent,
  toggleBookmark,
  listTags,
} from "../controllers/torrent";
import { createReport } from "../controllers/moderation";
import { updateAllTorrentScores } from "../controllers/scoringController";

// 导入评分和评论相关方法
import mongoose from "mongoose";
import Torrent from "../schema/torrent";
import Comment from "../schema/comment";

const router = express.Router();

export default (tracker) => {
  router.post("/upload", uploadTorrent);
  router.get("/info/:infoHash", fetchTorrent(tracker));
  router.get("/details/:torrentId", fetchTorrentDetailsByID(tracker));
  router.delete("/delete/:infoHash", deleteTorrent);
  router.post("/edit/:infoHash", editTorrent);
  router.post("/comment/:infoHash", addCommentTorrent);
  router.post("/vote/:infoHash/:vote", addVote);
  router.post("/unvote/:infoHash/:vote", removeVote);
  router.post("/report/:infoHash", createReport);
  router.post("/toggle-freeleech/:infoHash", toggleFreeleech);
  router.post("/bookmark/:infoHash", toggleBookmark);
  router.get("/latest", listLatest(tracker));
  router.get("/all", listAll);
  router.get("/search", searchTorrents(tracker));
  router.get("/tags", listTags);

  router.post("/update-all-scores", async (req, res) => {
    try {
      if (req.userRole !== "admin") {
        return res.status(403).json({ error: "只有管理员可以执行此操作" });
      }

      console.log("管理员触发了所有种子评分的更新");
      const result = await updateAllTorrentScores();

      return res.json({
        success: true,
        message: `成功更新了 ${result.updated} 个种子的评分`,
        updated: result.updated,
        total: result.total,
      });
    } catch (error) {
      console.error("更新评分失败:", error);
      return res.status(500).json({ error: "更新评分失败" });
    }
  });

  // 更新种子评分的API
  router.post("/update-score/:torrentId", async (req, res) => {
    try {
      const { torrentId } = req.params;

      console.log(`更新种子评分: ${torrentId}`);

      const torrent = await Torrent.findById(torrentId);
      if (!torrent) {
        return res.status(404).json({ error: "找不到种子" });
      }

      // 更新评分
      await torrent.updateScoreStats();

      return res.json({
        success: true,
        scoreStats: torrent.scoreStats,
        score: torrent.scoreStats.overallScore,
      });
    } catch (error) {
      console.error(`更新种子评分失败:`, error);
      return res.status(500).json({ error: "更新评分失败" });
    }
  });

  // 获取评论数量的API
  router.get("/comments-count/:infoHash", async (req, res) => {
    try {
      const { infoHash } = req.params;

      console.log(`获取种子评论数: ${infoHash}`);

      // 查找种子ID
      const torrent = await Torrent.findOne({ infoHash }, { _id: 1 }).lean();
      if (!torrent) {
        return res.status(404).json({ error: "找不到种子" });
      }

      // 查询评论数
      const count = await Comment.countDocuments({
        type: "torrent",
        parentId: torrent._id,
      });

      return res.json({ count });
    } catch (error) {
      console.error(`获取评论数失败:`, error);
      return res.status(500).json({ error: "获取评论数失败" });
    }
  });

  // 获取指定种子的评分详情
  router.get("/score/:torrentId", async (req, res) => {
    try {
      const { torrentId } = req.params;
      const torrent = await Torrent.findOne({ infoHash: torrentId });
      if (!torrent) {
        return res.status(404).json({ error: "找不到种子" });
      }
      return res.json({ scoreData: torrent.scoreStats });
    } catch (error) {
      console.error("获取评分详情失败:", error);
      return res.status(500).json({ error: "获取评分详情失败" });
    }
  });

  return router;
};
